package yartiss.engine.simulation.io;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import yartiss.engine.simulation.system.ITask;
import yartiss.engine.simulation.system.ITaskSet;
import yartiss.engine.simulation.system.SystemMetrics;

public class TasksetWriter {

	private final Writer writer;

	/**
	 * 
	 * @param dest
	 * @param pr
	 * @throws IOException
	 */
	public TasksetWriter(String dest) throws IOException {
		writer = new FileWriter(dest);
	}

	/**
	 * 
	 * @param dest
	 */
	public TasksetWriter(OutputStream dest) {
		writer = new OutputStreamWriter(dest);
	}

	/**
	 * 
	 * @param dest 
	 * @throws IOException
	 */
	public TasksetWriter(File dest) throws IOException {
		writer = new FileWriter(dest);
	}

	/**
	 * 
	 * @param taskset
	 * @param pr
	 * @throws IOException
	 */
	public void writeTaskSet(ITaskSet taskset, int pr) throws IOException {
		if (taskset.getAllTasksCount() == 0)
			return;
		List<ITask> set = new ArrayList<ITask>();
		for (ITask task : taskset) {
			set.add(task);
		}
		writeTaskSet(set, pr);
	}

	/**
	 * 
	 * @param taskset
	 * @param pr
	 * @throws IOException
	 */
	public void writeTaskSet(ITask[] taskset, int pr) throws IOException {
		writeTaskSet(Arrays.asList(taskset), pr);
	}

	/**
	 * 
	 * @param taskset
	 * @param pr
	 * @throws IOException
	 */
	public void writeTaskSet(Iterable<ITask> taskset, int pr)
			throws IOException {
		writer.write(pr + " " + SystemMetrics.utilisation(taskset) + " "
				+ SystemMetrics.energyUtilization(taskset, pr) + "\n");
		for (ITask task : taskset) {
			writer.write("firstrelease : " + task.getFirstRelease()
					+ " wcet : " + task.getWcet() + " wcee : " + task.getWcee()
					+ " period : " + task.getPeriod() + " deadline : "
					+ task.getDeadline() + " priorirty : " + task.getPriority()
					+ "\n");
		}
		writer.flush();
	}

	/**
	 * 
	 * @param sets
	 * @param pr
	 * @throws IOException
	 */
	public void writeAllTaskSets(Iterable<ITask[]> sets, int pr)
			throws IOException {
		for (ITask[] set : sets) {
			writeTaskSet(set, pr);
		}
	}

	/**
	 * 
	 */
	public void close() {
		try {
			writer.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
